#include "filedata.h"
#include <QFile>

FileData::FileData() :
    QObject(0)
{
}
FileData::~FileData()
{

}


int FileData::loadFromFilePath(const QString &filePath)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly) ){
        return -1;
    }
    QByteArray bytes = file.readAll();
    file.close();
    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(bytes,&error);
    if( error.error != QJsonParseError::NoError){
        return -2;
    }
    _filePath = filePath;
    _object = document.object();
    return 0;
}
int FileData::saveToFilePath(const QString &fp)
{
    QString filePath = fp.isEmpty()==true? _filePath:fp;

    QJsonDocument document;
    document.setObject(_object);
    QByteArray bytes = document.toJson();

    QFile file(filePath);
    if(!file.open(QIODevice::WriteOnly)){
        return -1;
    }
    file.write(bytes);
    file.close();
    return 0;
}

QString FileData::filePath()
{
    return _filePath;
}

QVariant FileData::valueWithKey(const QString &key)
{
    QVariant value;
    if(_object.find(key)!=_object.end()){
        QJsonValue jvalue = _object[key];
        value = jvalue.toVariant();
    }
    return value;
}

void FileData::setValueWithKey(const QString &key,const QVariant &value)
{
    QJsonValue jvalue = QJsonValue::fromVariant(value);
    _object[key] = jvalue;
}



bool FileData::boolValueWithKey(const QString &key)
{
    QVariant vptr = valueWithKey(key);
    return vptr.toBool();
}

void FileData::setBoolValueWithKey(const QString &key,bool value)
{
    QVariant vptr(value);
    setValueWithKey(key,vptr);
}

int FileData::intValueWithKey(const QString &key)
{
    QVariant vptr = valueWithKey(key);
    return vptr.toInt();
}

void FileData::setIntValueWithKey(const QString &key,int value)
{
    QVariant vptr(value);
    setValueWithKey(key,vptr);
}

QString FileData::stringValueWithKey(const QString &key)
{
    QVariant vptr = valueWithKey(key);
    return vptr.toString();
}

void FileData::setStringValueWithKey(const QString &key,const QString &value)
{
    QVariant vptr(value);
    setValueWithKey(key,vptr);
}
